package com.fa.ojcodesandbox;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;
import com.fa.ojcodesandbox.model.ExecuteCodeRequest;
import com.fa.ojcodesandbox.model.ExecuteCodeResponse;
import com.fa.ojcodesandbox.model.ExecuteMessage;
import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.async.ResultCallback;
import com.github.dockerjava.api.command.*;
import com.github.dockerjava.api.model.*;
import com.github.dockerjava.core.DockerClientBuilder;
import com.github.dockerjava.core.command.ExecStartResultCallback;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * ClassName: JavaDockerCodeSandbox
 * Package: com.fa.ojcodesandbox
 * Description: Java 代码沙箱实现-docker（直接 复用模板方法）
 *
 * @Author:
 * @Create: 2024/5/2 - 16:16
 * @Version: v1.0
 */
@Slf4j
@Component
public class JavaDockerCodeSandbox extends JavaCodeSandboxTemplate{

    // 首次初始化，是否需要下载镜像
    private static Boolean FIRST_INIT = true;

    @Override
    public ExecuteCodeResponse executeCode(ExecuteCodeRequest executeCodeRequest) {
        return super.executeCode(executeCodeRequest);
    }

    @Override
    public List<ExecuteMessage> runCompileAfterFile(String compileAfterFileParentPath, List<String> inputList) {
        // 3. 创建容器，把文件复制到容器内执行
        // 获取默认的 Docker Client
        DockerClient dockerClient = DockerClientBuilder.getInstance().build();
        // 拉取openjdk：8镜像     这里需要指定下载镜像的版本，否则会下载所有版本
        String imageName = "cnadiminti/dynamodb-local:latest";
        // 查看是否下载openjdk:8镜像
        ListImagesCmd listImagesCmd = dockerClient.listImagesCmd();
        List<Image> imageList = listImagesCmd.withShowAll(true).exec();
        for (Image image: imageList) {
            String[] imageRepoTags = image.getRepoTags();
            if (ArrayUtil.contains(imageRepoTags, imageName)) {
                // 如果 imageRepoTags包含 imageName，说明 需要的镜像已经下载，直接将 First_Init设置为false，这样就不需要重新下载镜像
                FIRST_INIT = false;
            }
        }
        if (FIRST_INIT) {
            PullImageCmd pullImageCmd = dockerClient.pullImageCmd(imageName);
            PullImageResultCallback pullImageResultCallback = new PullImageResultCallback() {
                @Override
                public void onNext(PullResponseItem item) {
                    log.info("下载镜像：" + item.getStatus());
                    super.onNext(item);
                }
            };
            try {
                pullImageCmd.exec(pullImageResultCallback)
                        .awaitCompletion();
            } catch (InterruptedException e) {
                log.warn("拉取镜像异常");
                throw new RuntimeException(e);
            }
        }

        // 创建容器
        CreateContainerCmd containerCmd = dockerClient.createContainerCmd(imageName);
        HostConfig hostConfig = new HostConfig();
        // 这里给每个docker容器设置内存大小。从这里就可以限制内存的分配；防止用户占用内存
        hostConfig.withMemory(100 * 1024 * 1024L);
        hostConfig.withMemorySwap(0L);
        // 这里给docker容器设置cpu的核数
        hostConfig.withCpuCount(1L);
        // 这里给主机设置绑定，相当于docker的数据卷挂载，将 Linux中用户代码的父目录绑定到docker的 /app目录
        hostConfig.setBinds(new Bind(compileAfterFileParentPath, new Volume("/app")));
        CreateContainerResponse createContainerResponse = containerCmd
                .withHostConfig(hostConfig)
                .withNetworkDisabled(true)//禁用网络，防止用户盗刷带宽
                .withAttachStdin(true)
                .withAttachStderr(true)
                .withAttachStdout(true)
                .withTty(true)
                .exec();
        String containerId = createContainerResponse.getId();
        if (StrUtil.isBlank(containerId)) {
            throw new RuntimeException("容器创建异常");
        }
        // 启动容器
        dockerClient.startContainerCmd(containerId).exec();

        // 在docker容器中正真要执行的命令是：docker exec jdk8的镜像名称 java -cp /app Main 1 3
        //执行命令获取结果
        List<ExecuteMessage> executeMessageList = new ArrayList<>();
        // maxMemory 用于存储内存的最大使用量
        final long[] maxUseMemory = {0};
        for (String inputArgs : inputList) {
            StopWatch stopWatch = new StopWatch();
            String[] inputArgsArray = inputArgs.split(" ");
            String[] cmdArray = ArrayUtil.append(new String[] { "java", "-cp", "/app", "Main"}, inputArgsArray);
            // 创建执行命令. 在docker中以交换模式 执行自己生成的Java指令
            ExecCreateCmdResponse execCreateCmdResponse = dockerClient.execCreateCmd(containerId)
                    .withCmd(cmdArray)
                    .withAttachStderr(true)
                    .withAttachStdin(true)
                    .withAttachStdout(true)
                    .exec();

            ExecuteMessage executeMessage = new ExecuteMessage();
            final String[] message = {null};
            final String[] errorMessage = {null};

            String execId = execCreateCmdResponse.getId();
            if (StrUtil.isBlank(execId)) {
                throw new RuntimeException("创建docker执行命令失败");
            }
            // 获取内存占用
            StatsCmd statsCmd = dockerClient.statsCmd(containerId);
            statsCmd.exec(new ResultCallback<Statistics>() {
                @Override
                public void onStart(Closeable closeable) {

                }
                @Override
                public void onNext(Statistics statistics) {
                    maxUseMemory[0] = statistics.getMemoryStats().getMaxUsage();
                }

                @Override
                public void onError(Throwable throwable) {

                }

                @Override
                public void onComplete() {
                }

                @Override
                public void close() throws IOException {

                }
            });
            ExecStartResultCallback execStartResultCallback = new ExecStartResultCallback() {
                @Override
                public void onNext(Frame frame) {
                    StreamType streamType = frame.getStreamType();
                    if (StreamType.STDERR.equals(streamType)) {
                        errorMessage[0] = new String(frame.getPayload());
                    } else {
                        // 因为new String(frame.getPayload())得到的结果总是带有 \n;如 ”3\n“
                        message[0] = new String(frame.getPayload()).replace("\n", "");
                    }
                    super.onNext(frame);
                }
            };
            try {
                stopWatch.start();
                // 在容器中运行代码时，设置等待时间，防止用户的程序超时，占用资源
                boolean awaitCompletion = dockerClient.execStartCmd(execId).exec(execStartResultCallback)
                        .awaitCompletion(TIME_OUT, TimeUnit.MILLISECONDS);
                stopWatch.stop();

//            System.out.println("awaitCompletion = " + awaitCompletion);如果程序执行时间超过超时时间，awaitCompletion = false
                if (!awaitCompletion) {
                    // 只要程序执行完毕，就要关闭容器
                    closeContainer(dockerClient);
                    //程序超时，直接return
                    throw new RuntimeException("程序执行时间超过最大等待时间");
                }
                maxRunTime = Math.max(maxRunTime, stopWatch.getLastTaskTimeMillis());
                maxMemory = maxUseMemory[0];
            } catch (InterruptedException e) {
                log.info("程序执行异常");
                throw new RuntimeException(e);
            } finally {
                // 执行完毕需要关闭资源
                statsCmd.close();
            }
            executeMessage.setMessage(message[0]);
            executeMessage.setErrorMessage(errorMessage[0]);
            executeMessageList.add(executeMessage);
        }
        // 只要程序执行完毕，就要关闭docker容器
        closeContainer(dockerClient);
        return executeMessageList;
    }

    /**
     * 程序执行完毕，关闭容器
     * @param dockerClient
     */
    private void closeContainer(DockerClient dockerClient) {
        // 停止容器，删除容器
        List<Container> containerList = dockerClient.listContainersCmd().withShowAll(true).exec();
        for (Container container :
                containerList) {
            String removeContainerId = container.getId().substring(0, 12);
            dockerClient.removeContainerCmd(removeContainerId).withForce(true).exec();
     }
    }
}
